#include "tileSelector.h"
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;

tileSelector::tileSelector()
{
	m_selected_rect.setSize(sf::Vector2f(m_tile_size - 2, m_tile_size - 2));
	m_selected_rect.setFillColor(sf::Color(0, 0, 0, 0));
	m_selected_rect.setOutlineColor(sf::Color::Yellow);
	m_selected_rect.setOutlineThickness(1);

	m_viewBox.setScale(2);
	setViewBoxPosition(0, 0);

	selectTile(0, 0);
}

void tileSelector::setTileSheet(sf::Texture* p_tilesheet)
{
	m_tilesheet_sprite.setTexture(*p_tilesheet);
	m_viewBox.setTileSheet(p_tilesheet);
}

void tileSelector::setBorderSheet(sf::Texture* p_tilesheet)
{
	m_viewBox.setBorderSheet(p_tilesheet);
}

void tileSelector::setViewBoxPosition(int p_x, int p_y)
{
	m_viewBox.setPosition(p_x, p_y);
}

void tileSelector::setPosition(int p_x, int p_y)
{
	m_position = sf::Vector2f(p_x, p_y);
	m_tilesheet_sprite.setPosition(m_position);
}

void tileSelector::processClick(float p_mouse_x, float p_mouse_y)
{
	int actual_x = p_mouse_x - m_position.x;
	int actual_y = p_mouse_y - m_position.y;

	sf::FloatRect tSize = m_tilesheet_sprite.getGlobalBounds();

	if (actual_x >= tSize.width)
		actual_x = tSize.width-1;
	if (actual_x < 0)
		actual_x = 0;

	if (actual_y >= tSize.height)
		actual_y = tSize.height-1;
	if (actual_y < 0)
		actual_y = 0;

	int tileX = actual_x/m_tile_size;
	int tileY = actual_y/m_tile_size;

	selectTile(tileX, tileY);
}

void tileSelector::selectTile(int p_tileX, int p_tileY)
{
	m_selected_rect.setPosition(m_position.x + p_tileX*m_tile_size + 1, m_position.y + p_tileY*m_tile_size + 1);
	m_current_tile = p_tileY * m_tilesheet_sprite.getGlobalBounds().width/m_tile_size + p_tileX;

	m_viewBox.setTile(p_tileX, p_tileY);
}

void tileSelector::draw(sf::RenderWindow* App)
{
	App->draw(m_tilesheet_sprite);
	App->draw(m_selected_rect);
	m_viewBox.draw(App);
}